package com.audaque.springboot.foshanupload.core.util;


import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


public class MemoryPagination {

    /**
     * 内存分页
     *
     * @param records  待分页的数据
     * @param pageNum  当前页码
     * @param pageSize 每页显示的条数
     * @return 分页之后的数据
     */
    public static <T> List<T> pagination(List<T> records, int pageNum, int pageSize) {
        if (CollectionUtils.isEmpty(records)) {
            return Collections.emptyList();
        }
        int totalCount = records.size();
        int remainder = totalCount % pageSize;
        int pageCount = (remainder > 0) ? totalCount/pageSize + 1 : totalCount/pageSize;
        if (remainder == 0) {
            return records.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        } else {
            if (pageNum == pageCount) {
                return records.stream().skip((pageNum - 1) * pageSize).limit(totalCount).collect(Collectors.toList());
            } else {
                return records.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
            }
        }
    }
}
